package com.even.camerarecoder

import android.media.AudioFormat
import android.media.AudioRecord
import android.media.MediaMetadataRetriever
import android.media.MediaRecorder
import com.evendai.loglibrary.Timber


object MediaUtil {

    /** 判断麦克风是有效，有效返回true，否则返回false */
    fun validateMicAvailability(): Boolean {
        var available = false
        val audioSource = MediaRecorder.AudioSource.MIC
        val sampleRateInHz = 44100
        val channelConfig = AudioFormat.CHANNEL_IN_MONO
        val audioFormat = AudioFormat.ENCODING_PCM_16BIT
        val minBufferSize = AudioRecord.getMinBufferSize(sampleRateInHz, channelConfig, audioFormat)
        val recorder = AudioRecord(audioSource, sampleRateInHz, channelConfig, audioFormat, minBufferSize)
        try {
            // 使用MediaRecorder正在录音时，调用此方法发现状态也是停止状态，所以这个状态不可信，具体还是要看能否启动录音来判断
            /*if (recorder.recordingState == AudioRecord.RECORDSTATE_STOPPED) {
                Timber.i("麦克风录制状态是停止状态")
            } else {
                Timber.i("麦克风录制状态不是停止状态")
            }*/

            if (recorder.state != AudioRecord.STATE_INITIALIZED) {
                Timber.fw("初始化AudioRecord失败")
                return false
            }

            recorder.startRecording() // 即使麦克风被占用，这里调用也不会抛异常。但如果没被占用，则录制状态会变成AudioRecord.RECORDSTATE_RECORDING
            if (recorder.recordingState == AudioRecord.RECORDSTATE_RECORDING) {
                available = true
                Timber.i("麦克风开始录制，没有被占用")
            } else {
                Timber.fw("麦克风没有开始录制，说明被占用")
            }
        } catch (e: Exception) {
            Timber.fw(e, "发生异常了，应该是麦克风被占用了")
        } finally {
            recorder.release()
        }
        return available
    }

    fun getMediaDuration(filePath: String): String? {
        var duration: String? = null
        val mmr = MediaMetadataRetriever()
        try {
            mmr.setDataSource(filePath)
            duration = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)
        } catch (ex: Exception) {
        } finally {
            mmr.release()
        }
        return duration
    }

}